<!DOCTYPE html>
<html>
<head>
    <title>{$app.name} - 卡密自助购买/开通/续费/购卡订单查询</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <link rel="icon" href="{$app.avatar}" type="image/x-icon">
    <style>
        @media screen and (max-width: 500px) {
            .el-message {
                min-width: 300px !important;
            }

            .el-message-box {
                width: 300px !important;
            }

            .el-dialog__wrapper .el-dialog {
                width: 95% !important;
            }

            .el-dialog__wrapper .el-dialog .el-dialog__body {
                overflow: auto
            }
        }

        @media screen and (min-width: 500px) {
            body{
                max-width: 800px;
                margin: auto !important;
            }
        }
    </style>
</head>
<body>
<div id="app">
    <div style="display: flex; justify-content: center; align-items: center;margin-top: 20px;">自助购买/开通/续费/订单查询</div>

    <?php if(empty($buy_config['common_buy_card']['close_buy_card']) && empty($input['hide_buy_card'])){?>
    <el-card style="margin-top: 15px;">
        <div slot="header" class="clearfix">
            <span>购买卡密</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="submit_buy">提交订单支付</el-button>
        </div>
        <el-form label-width="80px">
            <el-form-item :label="getValueLabel()">
                <el-input size="small" :disabled="buy.type==='6' || buy.type==='register_code'" type="number" v-model="buy.value" auto-complete="off">
                    <el-select style="width: 110px;" slot="append" v-model="buy.type" size="small" placeholder="卡密类型">
                        <?php foreach($CardTimeType as $CardTimeTypeItem){
                            if(!empty($buy_config['common_buy_card']['price'][$CardTimeTypeItem[0]])){
                        ?>
                        <el-option label="<?php echo $CardTimeTypeItem[1];?>" value="<?php echo $CardTimeTypeItem[0];?>"></el-option>
                        <?php }}?>
                    </el-select>
                </el-input>
            </el-form-item>
            <el-form-item label="购买数量">
                <el-input v-model="buy.num" type="number" placeholder="输入购买数量"></el-input>
            </el-form-item>
            <el-form-item label="支付方式">
                <el-select v-model="buy.pay_type" size="small" placeholder="选择付款方式">
                    <?php if(!empty($pay_config['wxpay']['open'])){?>
                    <el-option label="微信" :value="1"></el-option>
                    <?php }?>
                    <?php if(!empty($pay_config['alipay']['open'])){?>
                    <el-option label="支付宝" :value="2"></el-option>
                    <?php }?>
                    <?php if(!empty($pay_config['qqpay']['open'])){?>
                    <el-option label="QQ" :value="3"></el-option>
                    <?php }?>
                </el-select>
            </el-form-item>
            <el-form-item label="手机号码">
                <el-input v-model="buy.phone" :maxlength="11" :show-word-limit="true" placeholder="输入手机号码"></el-input>
            </el-form-item>
            <?php if(!empty($buy_config['common_buy_card']['query_password_must'])){?>
            <el-form-item label="取卡密码">
                <el-input v-model="buy.password" placeholder="设置取卡密码(后续查询订单用)"></el-input>
            </el-form-item>
            <?php }?>
            <el-form-item label="验证码">
                <el-input size="small" v-model="buy.code" placeholder="验证码" auto-complete="off">
                    <img :src="code_url" slot="append" alt="" style="height: 25px;" @click="getCode()">
                </el-input>
            </el-form-item>
        </el-form>
        <div style="display: flex; justify-content: center; align-items: center;margin-top: 20px;font-size: 10px;">订单金额:{{getPrice()}}</div>
    </el-card>
    <?php }?>

    <?php if(empty($input['hide_buy_card_order_query'])){?>
    <el-card style="margin-top: 15px;">
        <div slot="header" class="clearfix">
            <span>查询购卡订单</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="submit_query">提交订单查询</el-button>
        </div>
        <div>
            <el-form label-width="80px">
                <el-form-item label="查询信息">
                    <el-input size="small" v-model="query.value" placeholder="输入查询内容" auto-complete="off">
                        <el-select style="width: 100px;" slot="prepend" v-model="query.type" size="small" placeholder="查询方式">
                            <el-option label="订单编号" :value="1"></el-option>
                            <el-option label="手机号码" :value="2"></el-option>
                        </el-select>
                    </el-input>
                </el-form-item>
                <el-form-item label="验证码">
                    <el-input size="small" v-model="query.code" placeholder="验证码" auto-complete="off">
                        <img :src="code_url" slot="append" alt="" style="height: 25px;" @click="getCode()">
                    </el-input>
                </el-form-item>
            </el-form>
        </div>
        <div v-if="orderList.length">
            <el-table size="small" :data="orderList" highlight-current-row border >
                <el-table-column label="订单信息" width="240">
                    <template slot-scope="scope">
                        <div>
                            <div>订单编号：{{ scope.row.order_no }}</div>
                            <div>手机号码：{{ scope.row.user}}</div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="price" label="订单金额" width="100"> </el-table-column>
                <el-table-column prop="goods_num" label="购买数量" width="50"> </el-table-column>
                <el-table-column  label="订单时间" width="200">
                    <template slot-scope="scope">
                        <div>
                            <div>创建时间：{{ scope.row.create_time_str }}</div>
                            <div>付款时间：{{ scope.row.payment_time_str}}</div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="发货卡密" width="320">
                    <template slot-scope="scope">
                        <div>
                            <div v-if="scope.row.is_verify_query_password">
                                <el-button type="primary" icon="el-icon-view" @click="QueryCardBuyOrderDeliveryData(scope.row)">点击输入取卡密码获取卡密</el-button>
                            </div>
                            <div v-else>
                                <div v-for="(card,index) in scope.row.delivery_data.list">第{{index+1}}个卡密:{{card}}</div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div id="bottomDiv"></div>
        </div>
    </el-card>
    <?php }?>

    <?php if(empty($buy_config['common_buy_renewal']['close_renewal']) && empty($input['hide_renewal'])){?>
    <el-card style="margin-top: 15px;">
        <div slot="header" class="clearfix">
            <span>{{appInfo.type===0?"续费卡密":"开通/续费"}}</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="submit_renewal">提交订单支付</el-button>
        </div>
        <el-form label-width="80px">
            <el-form-item label="支付方式" v-if="appInfo.type===2">
                <el-select v-model="renewal.auth_type" size="small" placeholder="选择开通续费">
                    <el-option label="续费授权" value="renewal_auth"></el-option>
                    <el-option label="开通授权" value="new_auth"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item :label="getRenewalUserTitle()">
                <el-input v-model="renewal.user" :placeholder="'输入'+getRenewalUserTitle()"></el-input>
            </el-form-item>
            <el-form-item label="开通时长">
                <el-input size="small" :disabled="renewal.type==='6'" type="number" v-model="renewal.value" auto-complete="off">
                    <el-select style="width: 110px;" slot="append" v-model="renewal.type" size="small" placeholder="时长类型">
                        <?php foreach($CardTimeType as $CardTimeTypeItem){
                            if(!empty($buy_config['common_buy_renewal']['price'][$CardTimeTypeItem[0]]) && $CardTimeTypeItem[0]!='point'){
                        ?>
                        <el-option label="<?php echo $CardTimeTypeItem[1];?>" value="<?php echo $CardTimeTypeItem[0];?>"></el-option>
                        <?php }}?>
                    </el-select>
                </el-input>
            </el-form-item>
            <el-form-item label="支付方式">
                <el-select v-model="renewal.pay_type" size="small" placeholder="选择付款方式">
                    <?php if(!empty($pay_config['wxpay']['open'])){?>
                    <el-option label="微信" :value="1"></el-option>
                    <?php }?>
                    <?php if(!empty($pay_config['alipay']['open'])){?>
                    <el-option label="支付宝" :value="2"></el-option>
                    <?php }?>
                    <?php if(!empty($pay_config['qqpay']['open'])){?>
                    <el-option label="QQ" :value="3"></el-option>
                    <?php }?>
                </el-select>
            </el-form-item>
            <el-form-item label="验证码">
                <el-input size="small" v-model="renewal.code" placeholder="验证码" auto-complete="off">
                    <img :src="code_url" slot="append" alt="" style="height: 25px;" @click="getCode()">
                </el-input>
            </el-form-item>
        </el-form>
        <div style="display: flex; justify-content: center; align-items: center;margin-top: 20px;font-size: 10px;">订单金额:{{getRenewalPrice()}}</div>
    </el-card>
    <?php }?>

    <?php if(empty($buy_config['common_buy_renewal']['close_renewal']) && empty($input['hide_renewal'])){?>
    <el-card style="margin-top: 15px;">
        <div slot="header" class="clearfix">
            <span>充值积分</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="submit_renewal('point')">提交订单支付</el-button>
        </div>
        <el-form label-width="80px">
            <el-form-item :label="getRenewalUserTitle()">
                <el-input v-model="renewalPoint.user" :placeholder="'输入'+getRenewalUserTitle()"></el-input>
            </el-form-item>
            <el-form-item label="积分数量">
                <el-input size="small" type="number" v-model="renewalPoint.value" auto-complete="off" />
            </el-form-item>
            <el-form-item label="支付方式">
                <el-select v-model="renewalPoint.pay_type" size="small" placeholder="选择付款方式">
                    <?php if(!empty($pay_config['wxpay']['open'])){?>
                    <el-option label="微信" :value="1"></el-option>
                    <?php }?>
                    <?php if(!empty($pay_config['alipay']['open'])){?>
                    <el-option label="支付宝" :value="2"></el-option>
                    <?php }?>
                    <?php if(!empty($pay_config['qqpay']['open'])){?>
                    <el-option label="QQ" :value="3"></el-option>
                    <?php }?>
                </el-select>
            </el-form-item>
            <el-form-item label="验证码">
                <el-input size="small" v-model="renewalPoint.code" placeholder="验证码" auto-complete="off">
                    <img :src="code_url" slot="append" alt="" style="height: 25px;" @click="getCode()">
                </el-input>
            </el-form-item>
        </el-form>
        <div style="display: flex; justify-content: center; align-items: center;margin-top: 20px;font-size: 10px;">订单金额:{{getRenewalPointPrice()}}</div>
    </el-card>
    <?php }?>

    <div style="margin-top: 20px;"></div>
</div>
</body>
<script src="/static/js/vue2/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="/static/js/axios/axios.min.js"></script>
<script>
    new Vue({
        el: '#app',
        data: function () {
            return {
                appid: {$appid},//此处模板语法使用变量
                code_url: '',
                buy: {
                    type: '<?php echo $input["buy_type"] ?? "";?>',
                    num: Number('<?php echo $input["buy_num"] ?? "1";?>'),
                    value: Number('<?php echo $input["buy_value"] ?? "1";?>')
                },
                renewal: {
                    auth_type: '<?php echo $input["auth_type"] ?? "new_auth";?>',
                    type: '<?php echo $input["renewal_type"] ?? "";?>',
                    user: '<?php echo $input["renewal_user"] ?? "";?>',
                    value: Number('<?php echo $input["renewal_value"] ?? "1";?>')
                },
                renewalPoint: {
                    type: 'point',
                    user: '<?php echo $input["renewal_user"] ?? "";?>',
                    value: Number('<?php echo $input["renewal_point_value"] ?? "1";?>')
                },
                query: {
                    type: 2
                },
                orderList: [],
                appInfo:{},
            }
        },
        created() {
            this.getCode()
            let orderInfo='<?php echo bin2hex(json_encode($orderInfo));?>'
            orderInfo=JSON.parse(this.hexCharCodeToStr(orderInfo))
            if(orderInfo.id){
                this.orderList.push(orderInfo)
                this.scrollToBottom();
            }

            let appInfo='<?php echo bin2hex(json_encode($appInfo));?>'
            this.appInfo=JSON.parse(this.hexCharCodeToStr(appInfo))
        },
        methods: {
            scrollToBottom(){
                this.$nextTick(()=>{
                    let bottomDiv = this.$el.querySelector("#bottomDiv")
                    bottomDiv.scrollTop = bottomDiv.scrollHeight
                })
            },
            getValueLabel(){
                if(this.buy.type==='register_code'){
                    return '卡密面值';
                }else if(this.buy.type==='point'){
                    return '积分数量';
                }else{
                    return '卡密时长';
                }
            },
            hexCharCodeToStr(hexCharCodeStr) {
                var trimedStr = hexCharCodeStr.trim();
                var rawStr =
                    trimedStr.substr(0,2).toLowerCase() === "0x"
                        ?
                        trimedStr.substr(2)
                        :
                        trimedStr;
                var len = rawStr.length;
                if(len % 2 !== 0) {
                    alert("Illegal Format ASCII Code!");
                    return "";
                }
                var curCharCode;
                var resultStr = [];
                for(var i = 0; i < len;i = i + 2) {
                    curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
                    resultStr.push(String.fromCharCode(curCharCode));
                }
                return resultStr.join("");
            },
            async submit_buy() {
                const loading = this.$loading()
                await axios({
                    headers: {
                        'Content-Type': 'application/json;charset=UTF-8'
                    },
                    method: 'post',
                    url: '/index/buy/CreateCardBuyOrder',
                    data: {appid: this.appid, ...this.buy}
                }).then(response => {
                    if (response.data.code === 1) {
                        //window.open("/index/buy/pay/order_id/"+response.data.data.id)
                        location.href="/index/buy/pay/order_id/"+response.data.data.id
                    } else {
                        this.$message.error(response.data.msg)
                    }
                }).catch(error => {
                    console.log("提交失败 " + error)
                    this.$message.error("提交失败 " + error)
                })
                loading.close()
                this.getCode()
            },
            async submit_renewal(type='') {
                const loading = this.$loading()
                let post={appid: this.appid, ...this.renewal}
                if(type==='point'){
                    post={appid: this.appid, ...this.renewalPoint}
                }
                await axios({
                    headers: {
                        'Content-Type': 'application/json;charset=UTF-8'
                    },
                    method: 'post',
                    url: '/index/buy/CreateRenewalOrder',
                    data: post
                }).then(response => {
                    if (response.data.code === 1) {
                        //window.open("/index/buy/pay/order_id/"+response.data.data.id)
                        location.href="/index/buy/pay/order_id/"+response.data.data.id
                    } else {
                        this.$message.error(response.data.msg)
                    }
                }).catch(error => {
                    console.log("提交失败 " + error)
                    this.$message.error("提交失败 " + error)
                })
                loading.close()
                this.getCode()
            },
            getCode() {
                this.code_url = '/index/buy/code?t=' + Date.now()
            },
            async submit_query() {
                const loading = this.$loading()
                await axios({
                    headers: {
                        'Content-Type': 'application/json;charset=UTF-8'
                    },
                    method: 'post',
                    url: '/index/buy/QueryCardBuyOrder',
                    data: {appid: this.appid, ...this.query}
                }).then(response => {
                    if (response.data.code === 1) {
                        this.orderList = response.data.data
                        if(response.data.data.length===0){
                            this.$message.info('无记录')
                        }
                    } else {
                        this.$message.error(response.data.msg)
                    }
                }).catch(error => {
                    console.log("查询失败 " + error)
                    this.$message.error("查询失败 " + error)
                })
                loading.close()
                this.getCode()
            },
            QueryCardBuyOrderDeliveryData(row){
                this.$prompt('请输入购买时设置的取卡密码', '获取卡密信息', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(async({ value }) => {
                    const loading = this.$loading()
                    await axios({
                        headers: {
                            'Content-Type': 'application/json;charset=UTF-8'
                        },
                        method: 'post',
                        url: '/index/buy/QueryCardBuyOrderDeliveryData',
                        data: {appid: this.appid, order_no:row.order_no,password:value}
                    }).then(response => {
                        if (response.data.code === 1) {
                            row.delivery_data=response.data.data
                            row.is_verify_query_password=false
                            this.$message.success(response.data.msg)
                        } else {
                            this.$message.error(response.data.msg)
                        }
                    }).catch(error => {
                        console.log("查询失败 " + error)
                        this.$message.error("查询失败 " + error)
                    })
                    loading.close()
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            getPrice(){
                let priceList=<?php echo json_encode($buy_config['common_buy_card']['price'] ?? []); ?>

                if(priceList[this.buy.type]===null || priceList[this.buy.type]===undefined){
                    return '待计算';
                }
                let price=0;
                let str='';
                let value=1;
                if(this.buy.type!==6){
                    //不是永久卡
                    value=this.buy.value
                }
                price=priceList[this.buy.type]*value*this.buy.num
                str='(总价 '+price.toString()+' = 卡密单价'+priceList[this.buy.type]+'元 * 时长'+value+' * 数量'+this.buy.num+')';
                return price.toString()+str
            },
            getRenewalPrice(){
                let priceList=<?php echo json_encode($buy_config['common_buy_renewal']['price'] ?? []); ?>

                if(priceList[this.renewal.type]===null || priceList[this.renewal.type]===undefined){
                    return '待计算';
                }
                let price=0;
                let str='';
                let value=1;
                if(this.renewal.type!==6){ //不是永久卡
                    value=this.renewal.value
                }
                price=priceList[this.renewal.type]*value
                str='(总价 '+price.toString()+' = 单价'+priceList[this.renewal.type]+'元 * 时长'+value+')';
                return price.toString()+str
            },
            getRenewalPointPrice(){
                let priceList=<?php echo json_encode($buy_config['common_buy_renewal']['price'] ?? []); ?>

                let type='point'
                if(priceList[type]===null || priceList[type]===undefined){
                    return '待计算';
                }
                let price=0;
                let str='';
                price=priceList[type]*this.renewalPoint.value
                str='(总价 '+price.toString()+' = 单价'+priceList[type]+'元 * 积分'+this.renewalPoint.value+')';
                return price.toString()+str
            },
            getRenewalUserTitle(){
                if(this.appInfo.type===0){ //单码应用
                    return "续费卡密"
                }else if(this.appInfo.type===1){ //会员应用
                    return "用户账号"
                }else if(this.appInfo.type===2){ //授权应用
                    return "授权账户"
                }
            }
        }
    })
</script>
</html>
